package com.ys.peony.car300;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.ccrv.cber.sort.ItemData;
import com.ys.peony.R;
import com.ys.peony.app.YSConstant;
import com.ys.peony.base.contract.BasicActivity;
import com.ys.peony.base.contract.CarPledgeContract;
import com.ys.peony.enums.SwipeDirect;
import com.ys.peony.model.domain.CarAddInfo;
import com.ys.peony.model.domain.CityModel;
import com.ys.peony.model.domain.SaveCarModel;
import com.ys.peony.presenter.CarPledgePresenter;
import com.ys.peony.ui.widget.DatePicker;
import com.ys.peony.utils.LoadingProgressUtils;
import com.ys.peony.utils.SharePreferencesUtils;
import com.ys.peony.utils.ToastUtils;
import com.ys.peony.view.YsDialogItemModel;
import com.ys.peony.view.inter.YsDailogClickListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class CarInfo2Activity extends BasicActivity<CarPledgeContract.iCarInfoView, CarPledgePresenter> implements CarPledgeContract.iCarInfo2View, View.OnClickListener, DatePicker.DatePickerCallBack, YsDailogClickListener {

    private final static String TYPE_COMPANY = "1";//公司
    private final static String TYPE_PERSONAL = "2";//个人；

    @BindView(R.id.rootview)
    ScrollView rootView;

    @BindView(R.id.car_city)
    RelativeLayout car_city;
    @BindView(R.id.car_area)
    RelativeLayout car_area;
    @BindView(R.id.signin_time)
    RelativeLayout signin_time;
    @BindView(R.id.car_qs)
    RelativeLayout car_qs;
    @BindView(R.id.fazheng_time)
    RelativeLayout fazheng_time;
    @BindView(R.id.chuchang_time)
    RelativeLayout chuchang_time;

    @BindView(R.id.car_city_tv)
    TextView car_city_tv;
    @BindView(R.id.car_area_tv)
    TextView car_area_tv;
    @BindView(R.id.signin_time_tv)
    TextView signin_time_tv;
    @BindView(R.id.car_qs_tv)
    TextView car_qs_tv;
    @BindView(R.id.fazheng_time_tv)
    TextView fazheng_time_tv;
    @BindView(R.id.chuchang_time_tv)
    TextView chuchang_time_tv;

    @BindView(R.id.kilo_et)
    EditText kilo_et;
    @BindView(R.id.car_number_et)
    EditText car_number_et;
    @BindView(R.id.car_buy_et)
    EditText car_buy_et;
    @BindView(R.id.drivernum_et)
    EditText drivernum_et;
    @BindView(R.id.qs_et)
    EditText qs_et;

    @BindView(R.id.save)
    Button save;

    public final static int CODE_GET_CITY = 1;
    public final static int CODE_SAVE_CAR = 2;
    private DatePicker datePicker = null;
    private YsDialogItemModel mDialogItemModel;
    private String selectYearStr = "", selectMonthStr = "", selectDayStr = "";

    @Override
    protected CarPledgePresenter initPresenter() {
        return new CarPledgePresenter();
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_car_info2;
    }

    @Override
    protected void initView() {
        super.initView();
        initData();
        initWidget();
        initListener();
    }

    private void initData() {
        /*CarAddInfo carAddInfo = CarDataManager.getInstance().getmCarAddInfo();
        if(carAddInfo != null) {
            kilo_et.setText(carAddInfo.getKilometer().toString().trim());
            car_number_et.setText(carAddInfo.getPlate_number().toString().trim());
            car_buy_et.setText(carAddInfo.getPrice().toString().trim());
            drivernum_et.setText(carAddInfo.getEngine_number().toString().trim());
            signin_time_tv.setText(carAddInfo.getTime_buying().toString().trim());
            car_qs_tv.setText(carAddInfo.getOwnership_tag().toString().trim());
            qs_et.setText(carAddInfo.getOwnership_person().toString().trim());
            fazheng_time_tv.setText(carAddInfo.getTime_awarded().toString().trim());
            chuchang_time_tv.setText(carAddInfo.getMake_date().toString().trim());
        }*/
    }

    private void initWidget() {
        mDialogItemModel = new YsDialogItemModel(this, this);
    }

    private void initListener() {
        car_city.setOnClickListener(this);
        car_area.setOnClickListener(this);
        signin_time.setOnClickListener(this);
        car_qs.setOnClickListener(this);
        fazheng_time.setOnClickListener(this);
        chuchang_time.setOnClickListener(this);
        kilo_et.setOnClickListener(this);
        save.setOnClickListener(this);
        car_number_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                car_number_et.removeTextChangedListener(this);//解除文字改变事件
                car_number_et.setText(charSequence.toString().toUpperCase());
                car_number_et.setSelection(charSequence.toString().length());//重新设置光标位置
                car_number_et.addTextChangedListener(this);//重新绑
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        drivernum_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                drivernum_et.removeTextChangedListener(this);//解除文字改变事件
                drivernum_et.setText(charSequence.toString().toUpperCase());
                drivernum_et.setSelection(charSequence.toString().length());//重新设置光标位置
                drivernum_et.addTextChangedListener(this);//重新绑
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    public void onClick(View view) {
        List<String> items;
        List<ItemModel> itemModels;
        datePicker = null;
        switch (view.getId()) {
            case R.id.car_city:
                if (CarDataManager.getInstance().getmCityModel() == null) {
                    LoadingProgressUtils.showProgressDialog(this);
                    presenter.getCity();
                } else {
                    jumpCitySelect();
                }
                break;
            case R.id.car_area:
                if (CarDataManager.getInstance().getCarDetailModel() != null) {
                    itemModels = presenter.getItemModel(CarDataManager.getInstance().getCarDetailModel().getAreaList(), R.id.car_area);
                    if (itemModels != null && itemModels.size() > 0) {
                        mDialogItemModel.setItemModels(itemModels, YSConstant.POP_TYPE_AREA);
                    }
                }
                break;
            case R.id.signin_time:
                if (datePicker == null) {
                    datePicker = new DatePicker(this, this, YSConstant.POP_DATE_SIGNTIME);
                }
                datePicker.show(rootView, selectYearStr, selectMonthStr, selectDayStr);
                break;
            case R.id.car_qs:
                itemModels = presenter.getItemModel(CarDataManager.getInstance().getCarDetailModel().getVehicleOwnershopTagList(), R.id.car_qs);
                if (itemModels != null && itemModels.size() > 0) {
                    mDialogItemModel.setItemModels(itemModels, YSConstant.POP_TYPE_QS);
                }
                break;
            case R.id.fazheng_time:
                if (datePicker == null) {
                    datePicker = new DatePicker(this, this, YSConstant.POP_DATE_FAZHENGTIME);
                }
                datePicker.show(rootView, selectYearStr, selectMonthStr, selectDayStr);
                break;
            case R.id.chuchang_time:
                if (datePicker == null) {
                    datePicker = new DatePicker(this, this, YSConstant.POP_DATE_CHUCHANGTIME);
                }
                datePicker.show(rootView, selectYearStr, selectMonthStr, selectDayStr);
                break;
            case R.id.save:
                if (checkCarInfo()) {
                    LoadingProgressUtils.showProgressDialog(this);
                    saveCarInfo();
                    presenter.addPledgeCar();
                } else {
                    ToastUtils.showToast("请完善必要信息");
                }
                break;
            case R.id.kilo_et:
                kilo_et.setCursorVisible(true);
                break;
        }
    }

    @Override
    public void onResult(int code) {
        switch (code) {
            case CODE_GET_CITY:
                jumpCitySelect();
                break;
            case CODE_SAVE_CAR:
                SaveCarModel saveCarModel = CarDataManager.getInstance().getSaveCarModel();
                if (saveCarModel != null) {
                    SaveCarModel.MortgageListBean mortgageListBean = saveCarModel.getMortgageList().get(0);
                    if (mortgageListBean.getEstimation() == 0) {
                        ToastUtils.showToast(this.getResources().getString(R.string.car_error_tips));
                    }
                    jumpBaoDanPage();
                }
                break;

        }
    }


    @Override
    public void onSuccess() {

    }

    private void jumpCitySelect() {
        String[] items = getCityItems();
        if (items != null && items.length > 0) {
            Bundle bundle = new Bundle();
            bundle.putStringArray(ListSelectActivity.ITEM_PARAM, items);
            skipToTargetPage(ListSelectActivity.class, bundle, SwipeDirect.DIRECT_LEFT, true);
        }
    }

    private void jumpBaoDanPage() {
        skipToTargetPage(BaoDanActivity.class, null);
    }

    private String[] getCityItems() {
        List<String> items = new ArrayList<>();
        CityModel cityModel = CarDataManager.getInstance().getmCityModel();
        if (cityModel != null && cityModel.getData() != null) {
            List<CityModel.DataBean> cityModelData = cityModel.getData();
            for (int i = 0; i < cityModelData.size(); i++) {
                List<CityModel.DataBean.CityInfosBean> cityInfosBeen = cityModelData.get(i).getCityInfos();
                for (int j = 0; j < cityInfosBeen.size(); j++) {
                    CityModel.DataBean.CityInfosBean cityInfoBean = cityInfosBeen.get(j);
                    if (cityInfoBean != null && !TextUtils.isEmpty(cityInfoBean.getCity_name())) {
                        items.add(cityInfoBean.getCity_name());
                    }
                }
            }
        }
        String[] result = new String[items.size()];
        items.toArray(result);
        return result;
    }

    private CityModel.DataBean.CityInfosBean getSelectCityInfoByName(String cityName) {
        CityModel cityModel = CarDataManager.getInstance().getmCityModel();
        if (cityModel != null && cityModel.getData() != null) {
            List<CityModel.DataBean> cityModelData = cityModel.getData();
            for (int i = 0; i < cityModelData.size(); i++) {
                List<CityModel.DataBean.CityInfosBean> cityInfosBeen = cityModelData.get(i).getCityInfos();
                for (int j = 0; j < cityInfosBeen.size(); j++) {
                    CityModel.DataBean.CityInfosBean cityInfoBean = cityInfosBeen.get(j);
                    if (cityInfoBean != null && cityName.equals(cityInfoBean.getCity_name())) {
                        return cityInfoBean;
                    }
                }
            }
        }
        return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ListSelectActivity.RESULT_OK) {
            ItemData carType = (ItemData) data.getSerializableExtra(ListSelectActivity.ITEM_PARAM);
            if (carType != null && !TextUtils.isEmpty(carType.getCar_title())) {
                car_city_tv.setText(carType.getCar_title());
                CityModel.DataBean.CityInfosBean cityInfosBean = getSelectCityInfoByName(carType.getCar_title());
                if (cityInfosBean != null) {
                    CarAddInfo carAddInfo = CarDataManager.getInstance().getmCarAddInfo();
                    carAddInfo.setProv_id(String.valueOf(cityInfosBean.getProv_id()));
                    if (cityInfosBean.getProv_name() != null) {
                        carAddInfo.setProv_id_desr(cityInfosBean.getProv_name().toString());
                    }
                    carAddInfo.setCity_id(String.valueOf(cityInfosBean.getCity_id()));
                    carAddInfo.setCity_id_desr(cityInfosBean.getCity_name());
                }
            }
        }
    }

    @Override
    public void datePickerConfirmOnclick(String yearStr, String monthStr, String dayStr, int tag) {
        selectYearStr = yearStr;
        selectMonthStr = monthStr;
        selectDayStr = dayStr;
        String time = yearStr + "-" + monthStr + "-" + dayStr;
        switch (tag) {
            case YSConstant.POP_DATE_SIGNTIME:
                signin_time_tv.setText(time);
                break;
            case YSConstant.POP_DATE_FAZHENGTIME:
                fazheng_time_tv.setText(time);
                break;
            case YSConstant.POP_DATE_CHUCHANGTIME:
                chuchang_time_tv.setText(time);
                break;

        }

    }

    @Override
    public void datePickerCancelOnclick() {

    }

    @Override
    public void clickDialogItemModel(int type, ItemModel itemModel) {
        if (itemModel == null) {
            return;
        }
        switch (type) {
            case YSConstant.POP_TYPE_AREA:
                car_area_tv.setText(itemModel.getText());
                CarDataManager.getInstance().getmCarAddInfo().setAttribution_area(itemModel.getVal());
                break;
            case YSConstant.POP_TYPE_QS:
                if (TYPE_COMPANY.equals(itemModel.getVal())) {
                    qs_et.setCursorVisible(true);
                    qs_et.setFocusable(true);
                    qs_et.setFocusableInTouchMode(true);

                } else if (TYPE_PERSONAL.equals(itemModel.getVal())) {
                    qs_et.setCursorVisible(false);
                    qs_et.setFocusable(false);
                    qs_et.setFocusableInTouchMode(false);
                    qs_et.setText(CarDataManager.getInstance().getLoanName());
                }
                car_qs_tv.setText(itemModel.getText());
                CarDataManager.getInstance().getmCarAddInfo().setOwnership_tag(itemModel.getVal());
                break;
        }
    }

    private Boolean checkCarInfo() {
        if (TextUtils.isEmpty(car_city_tv.getText().toString().trim()) ||
                TextUtils.isEmpty(fazheng_time_tv.getText().toString().trim()) ||
                TextUtils.isEmpty(kilo_et.getText().toString().trim()) ||
                TextUtils.isEmpty(car_number_et.getText().toString().trim()) ||
                TextUtils.isEmpty(car_buy_et.getText().toString().trim()) ||
                TextUtils.isEmpty(drivernum_et.getText().toString().trim()) ||
                TextUtils.isEmpty(signin_time_tv.getText().toString().trim()) ||
                TextUtils.isEmpty(car_qs_tv.getText().toString().trim()) ||
                TextUtils.isEmpty(qs_et.getText().toString().trim()) ||
                TextUtils.isEmpty(car_area_tv.getText().toString().trim())) {
            return false;
        }
        return true;
    }

    private void saveCarInfo() {
        CarAddInfo carAddInfo = CarDataManager.getInstance().getmCarAddInfo();
        if (carAddInfo != null) {
            carAddInfo.setKilometer(kilo_et.getText().toString().trim());
            carAddInfo.setPlate_number(car_number_et.getText().toString().trim());
            carAddInfo.setPrice(car_buy_et.getText().toString().trim());
            carAddInfo.setEngine_number(drivernum_et.getText().toString().trim());
            carAddInfo.setTime_buying(signin_time_tv.getText().toString().trim());
            carAddInfo.setOwnership_person(qs_et.getText().toString().trim());
            if (!TextUtils.isEmpty(fazheng_time_tv.getText().toString().trim())) {
                carAddInfo.setTime_awarded(fazheng_time_tv.getText().toString().trim());
            }
            if (!TextUtils.isEmpty(chuchang_time_tv.getText().toString().trim())) {
                carAddInfo.setMake_date(chuchang_time_tv.getText().toString().trim());
            }
            if (!TextUtils.isEmpty(SharePreferencesUtils.getInstance().getUserId())) {
                carAddInfo.setUserID(SharePreferencesUtils.getInstance().getUserId());
            }
        }
    }

    @Override
    public void onFail(String msg) {
        ToastUtils.showToast(msg);
    }
}
